package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.pojo.Cart;
import com.qf.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 29125
 * @version V1.0
 * @Project java2203
 * @Package com.qf.dao.impl
 * @Description:
 * @Date 2022/5/25 17:22
 */
public class CartDaoImpl implements CartDao {
    //反射，创建dbUtils工具类
    private QueryRunner queryRunner=new QueryRunner(DBUtil.getDataSource());
    //修改购物车
    @Override
    public void updateCart(Cart cart) {
        String sql=" update tb_cart set num=? ,money=? where cid=? ";
        try {
            queryRunner.update(sql,cart.getNum(),cart.getMoney(),cart.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //添加购物车商品
    @Override
    public void insertCart(Cart cart) {
        String sql=" insert into tb_cart (uid,pid,num,money) value (?, ?, ?, ?) ";
        try {
            queryRunner.update(sql,cart.getUid(),cart.getPid(),cart.getNum(),cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //通过用户id和商品id查询购物车对象
    @Override
    public Cart findCartByUidAndPid(Integer uid, Integer pid) {
        String sql=" select * from tb_cart where uid=? and pid=? ";
        try {
            Cart cart=queryRunner.query(sql,new BeanHandler<Cart>(Cart.class),uid,pid);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Cart findById(Integer id) {
        String sql=" select * from tb_cart where cid=? ";
        try {
            Cart cart=queryRunner.query(sql,new BeanHandler<Cart>(Cart.class),id);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void deleteById(Integer id) {
        String sql=" delete from tb_cart where cid=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCartListByUid(Integer id) {
        String sql=" select * from tb_cart where uid=? ";
        try {
            List<Cart> list=queryRunner.query(sql,new BeanListHandler<Cart>(Cart.class),id);
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
}
